﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk;
using RibbonEditor.Managers;
using Microsoft.Xrm.Sdk.Metadata;

namespace RibbonEditor.Forms.Entities
{
    public partial class EntitiesPicker : Form
    {
        public List<EntityMetadata> SelectedEntities { get; set; }

        public EntitiesPicker(MetadataManager mManager)
        {
            InitializeComponent();
            this.FillEntities(mManager);
        }

        private void FillEntities(MetadataManager mManager)
        {
            foreach (EntityMetadata emd in mManager.EntityCache)
            {
                if (emd.IsCustomizable.Value && emd.DisplayName.UserLocalizedLabel != null)
                {
                    ListViewItem item = new ListViewItem()
                    {
                        Text = emd.DisplayName.UserLocalizedLabel.Label,
                        Tag = emd
                    };

                    this.lvSelectedEntities.Items.Add(item);
                }
            }

            this.lvSelectedEntities.Sort();
        }

        private void btnValidate_Click(object sender, EventArgs e)
        {
            if (this.lvSelectedEntities.CheckedItems.Count == 0)
            {
                MessageBox.Show(this, "Please select at least one entity!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                this.SelectedEntities = new List<EntityMetadata>();

                foreach (ListViewItem item in this.lvSelectedEntities.CheckedItems)
                {
                    this.SelectedEntities.Add((EntityMetadata)item.Tag);
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
